package com.ujson.chat.client.command;

import com.ujson.base.common.utils.EnumUtil;
import com.ujson.chat.common.enums.ConsoleCommandType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <h3>ujson-parent</h3>
 * <p>控制台菜单命令</p>
 *
 * @author JerryLiu  a1031757312@gmail.com
 * @version 1.0
 * @date 2021-11-22 21:26
 */
@Service
public class ClientMenuConsoleCommand extends ConsoleCommand<String> {
    private Map<ConsoleCommandType, ConsoleCommand> commandMap;
    private String menuTips;
    private String menuInputPattern = "[1-4]";

    @Autowired
    public ClientMenuConsoleCommand(List<ConsoleCommand> consoleCommandList) {
        Collections.reverse(consoleCommandList);
        commandMap = consoleCommandList.stream().collect(Collectors.toMap(v -> v.getType(), v -> v));
        StringBuffer menuTips = new StringBuffer();
        menuTips.append("[menu] ");
        Set<ConsoleCommandType> commandTypes = commandMap.keySet();
        for (ConsoleCommandType commandType : commandTypes) {
            menuTips.append(commandType.getKey()).append(" -> ")
                    .append(commandType.getTips()).append(" |");
        }
        this.menuTips = menuTips.toString();
    }

    public ConsoleCommandType getType() {
        return ConsoleCommandType.MENU;
    }

    public String getInput() {
        return this.getInputString();
    }

    @Override
    public String getMatchPattern() {
        return this.menuInputPattern;
    }

    public void exec(Scanner scanner) {
        System.err.println("请输入命令:");
        System.err.println(this.menuTips);
        while (!checkCommand(this.setInputString(scanner.next()))) {
            System.err.println("菜单命令输入不正确, 请重新输入:");
        }
        ConsoleCommandType commandType = EnumUtil.getEnum(ConsoleCommandType.class, Integer.valueOf(getInput()));
        commandMap.get(commandType).exec(scanner);
    }
}
